package com.unione.heathrobot

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.CountDownTimer
import android.view.MotionEvent
import com.unione.unione_base.view.AppBaseActivity

open class BaseCountDownActivity : AppBaseActivity() {

    var countDownTimer: CountDownTimer? = null
    lateinit var context: Context
    private val advertisingTime: Long = 60 * 1000

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        context = this
    }

    override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
        when (ev?.action) {
            MotionEvent.ACTION_DOWN -> {
                if (countDownTimer != null) {
                    countDownTimer!!.cancel()

                }
            }

            MotionEvent.ACTION_UP -> startAD()
        }
        return super.dispatchTouchEvent(ev)
    }

    private fun startAD() {
        if (countDownTimer == null) {
            countDownTimer = object : CountDownTimer(advertisingTime, 1000L) {
                override fun onTick(millisUntilFinished: Long) {

                }

                override fun onFinish() {
                    startActivity(Intent(context, WelcomeActivity::class.java))
                }

            }
            countDownTimer!!.start()
        } else countDownTimer!!.start()
    }

    override fun onResume() {
        super.onResume()
        startAD()
    }

    override fun onPause() {
        super.onPause()
        if (countDownTimer != null) {
            countDownTimer!!.cancel()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        if (countDownTimer != null) {
            countDownTimer!!.cancel()
        }
    }
}